package cn.falcon.fmobi.console.controller;

import cn.falcon.fmobi.biz.common.ResultSetList;
import cn.falcon.fmobi.biz.service.CreativeService;
import cn.falcon.fmobi.biz.vo.*;
import cn.falcon.fmobi.console.common.RestfulJsonModelAndView;
import cn.falcon.fmobi.console.common.Result;
import cn.falcon.fmobi.console.constant.UrlConstant;
import cn.falcon.fmobi.console.exception.ParamValidateException;
import cn.falcon.fmobi.console.requestparam.CreativeProdcutParam;
import cn.falcon.fmobi.console.requestparam.CreativeQuery;
import cn.falcon.fmobi.console.requestparam.CreativeStatusParam;
import cn.falcon.fmobi.console.requestparam.GetCreativeParam;
import cn.falcon.fmobi.dao.enumration.AdFormat;
import cn.falcon.fmobi.dao.enumration.MaterialType;
import cn.falcon.fmobi.dao.model.CreativeAndStrategyListModel;
import cn.falcon.fmobi.dao.model.CreativeProductModel;
import cn.falcon.fmobi.dao.po.CreativeMaterial;
import cn.falcon.fmobi.dao.util.ValidateUtil;
import cn.falcon.marketing.api.enumeration.ProductType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 创意管理
 * @author zhaohelong
 */
@Controller
@RequestMapping(UrlConstant.CREATIVE_URL)
public class CreativeCtrl extends BaseCtrl {

    @Autowired
    private CreativeService creativeService;


    /**
     * 新建创意
     * @param param
     * @return
     * @throws ParamValidateException
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public ModelAndView add(@RequestBody CreativeInfoVo param)throws ParamValidateException,UnsupportedEncodingException{
        //校验参数
        creativeParamValidation(param);
        DropdownVo vo = creativeService.saveCreative(param);
        return RestfulJsonModelAndView.buildJsonModelAndView(vo);
    }

    /**
     * 编辑创意
     * @param param
     * @return
     */
    @RequestMapping(value = "/update",method = RequestMethod.PUT)
    public ModelAndView edit(@RequestBody CreativeInfoVo param)throws ParamValidateException,UnsupportedEncodingException{
        creativeParamValidation(param);
        creativeService.updateCreative(param);
        return RestfulJsonModelAndView.buildJsonModelAndView();
    }

    /**
     * 查询创意信息接口
     * @param id
     * @return
     */
    @RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
    public ModelAndView findOne(@PathVariable("id") Integer id){
        CreativeInfoVo creativeInfoVo=creativeService.findById(id);
        return RestfulJsonModelAndView.buildJsonModelAndView(creativeInfoVo);
    }

    /**
     * 快捷切换创意状态接口
     * @return
     */
    @RequestMapping(value = "/status",method = RequestMethod.PUT)
    public ModelAndView editStatus(@RequestBody CreativeStatusParam param){
        creativeService.editStatus(param.getMap());
        return RestfulJsonModelAndView.buildJsonModelAndView();
    }

    /**
     * 创意列表接口
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public ModelAndView list(CreativeQuery query){
        ResultSetList<CreativeListVo> creativeList = creativeService.findCreativeList(query.getSearchMap(), query.getPageInfo(), true);
        return RestfulJsonModelAndView.buildJsonModelAndView(creativeList);
    }

    /**
     * 策略相关接口
     * @return
     */
    @RequestMapping(value = "/selectCreative",method = RequestMethod.GET)
    public ModelAndView list(GetCreativeParam getCreativeParam){
        List<CreativeAndStrategyListModel> creativeAndStrategyListModelList =
                creativeService.creativeAndStrategyListModelList(getCreativeParam.getCampaignId(), getCreativeParam.getId());
        return RestfulJsonModelAndView.buildJsonModelAndView(creativeAndStrategyListModelList);
    }

    /**
     * 根据广告位ID查询模板元素信息
     * @param adSpaceId
     * @return
     */
    @RequestMapping(value = "/templateSpec/{adSpaceId}",method = RequestMethod.GET)
    public ModelAndView getTemplateSpecList(@PathVariable("adSpaceId") Integer adSpaceId){
        CreativeTemplateSpeDetail list = creativeService.findTemplateSpecListByAdSpaceId(adSpaceId);
        return RestfulJsonModelAndView.buildJsonModelAndView(list);
    }

    /**
     * 根据appId和标的物类型获取广点通标的物子标的物信息
     * @return
     */
    @RequestMapping(value = "/gdt/product/list",method = RequestMethod.GET)
    public ModelAndView getGdtProductList(CreativeProdcutParam param){
        List<Subordinate> subordinateList = creativeService.getSubordinateList(param.getSearchMap());
        return RestfulJsonModelAndView.buildJsonModelAndView(subordinateList);
    }

    /**
     * 获取标的物类型
     * @return
     */
    @RequestMapping(value = "/product/list",method = RequestMethod.GET)
    public ModelAndView getProductList(){
        List<ProductVo> productList = creativeService.getProductList();
        return RestfulJsonModelAndView.buildJsonModelAndView(productList);
    }

    /**
     * 根据推广计划ID查询出对应的标的物类型信息
     * @param promotionPlanId
     * @return
     */
    @RequestMapping(value = "/get/product/{promotionPlanId}",method = RequestMethod.GET)
    private ModelAndView getProductInfo(@PathVariable("promotionPlanId") Integer promotionPlanId){
        CreativeProductModel product = creativeService.findProductByPromotionPlanId(promotionPlanId);
        return RestfulJsonModelAndView.buildJsonModelAndView(product);
    }

    //创意参数必填项验证
    private void creativeParamValidation(CreativeInfoVo creativeInfoVo)throws ParamValidateException,UnsupportedEncodingException{
        //创意名称必填
        if (StringUtils.isEmpty(creativeInfoVo.getName())){
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"name","Param.err.creative.name.not.null");
        }
        //验证创意名称长度
        if (!StringUtils.isEmpty(creativeInfoVo.getName())&&ValidateUtil.checkLength(creativeInfoVo.getName(),120)){
            throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"name", "Param.err.creative.name.max");
        }
        //创意描述长度验证
        if (!StringUtils.isEmpty(creativeInfoVo.getDescription()) && ValidateUtil.checkLength(creativeInfoVo.getDescription(),250)){
            throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"description", "Param.err.creative.description.max");
        }
        //所属推广计划验证
        if (creativeInfoVo.getPromotionPlanId()==null||creativeInfoVo.getPromotionPlanId()==0){
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"promotionPlanId","Param.err.creative.promotion.not.null");
        }
        //验证标的物
        if (creativeInfoVo.getMarkType()==null||creativeInfoVo.getMarkType()==0){
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"markType","Param.err.creative.markType.not.null");
        }

        //如果标的物类型是Android或者IOS
        if (ProductType.mappings.get(creativeInfoVo.getMarkType())==ProductType.PRODUCT_TYPE_APP_ANDROID_OPEN_PLATFORM||
                ProductType.mappings.get(creativeInfoVo.getMarkType())==ProductType.PRODUCT_TYPE_APP_IOS){
            //验证应用名称是否为空
            if (StringUtils.isEmpty(creativeInfoVo.getAppName())){
                throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"appName","Param.err.creative.appName.not.null");
            }
            //验证应用名称长度
            if (!StringUtils.isEmpty(creativeInfoVo.getAppName())&&ValidateUtil.checkLength(creativeInfoVo.getAppName(),200)){
                throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"appName", "Param.err.creative.appName.max");
            }
            //验证下载地址
            if (StringUtils.isEmpty(creativeInfoVo.getTargetUrl())){
                throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"targetUrl","Param.err.creative.downloadUrl.not.null");
            }
            //验证目标地址或下载地址的长度
            if (!StringUtils.isEmpty(creativeInfoVo.getTargetUrl())&&ValidateUtil.checkLength(creativeInfoVo.getTargetUrl(),500)){
                throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"targetUrl", "Param.err.creative.downloadUrl.max");
            }
            //验证App Id是否为空
            if (StringUtils.isEmpty(creativeInfoVo.getAppId())){
                throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"appId", "Param.err.creative.appId.not.null");
            }
            //验证App ID的长度
            if (!StringUtils.isEmpty(creativeInfoVo.getAppId())&&ValidateUtil.checkLength(creativeInfoVo.getAppId(),50)){
                throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"appId", "Param.err.creative.appId.max");
            }
        }
        //如果标的物类型是普通链接或微信品牌页
        if (ProductType.mappings.get(creativeInfoVo.getMarkType())==ProductType.PRODUCT_TYPE_LINK
                || ProductType.mappings.get(creativeInfoVo.getMarkType())==ProductType.PRODUCT_TYPE_LINK_WECHAT){
            //目标地址验证
            if(StringUtils.isEmpty(creativeInfoVo.getTargetUrl())){
                throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"targetUrl","Param.err.creative.targetUrl.not.null");
            }
            //验证目标地址长度
            if (!StringUtils.isEmpty(creativeInfoVo.getTargetUrl())&&ValidateUtil.checkLength(creativeInfoVo.getTargetUrl(),1023)){
                throw new ParamValidateException(Result.ERR_INVALID_PARAMETER,"targetUrl", "Param.err.creative.targetUrl.max");
            }
        }
        //验证参数adFormat
        if (creativeInfoVo.getAdFormat()==null||creativeInfoVo.getAdFormat()==0){
            throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"adFormat","Param.err.creative.adFormat.not.null");
        }
        //验证素材基本信息
        if (new Integer(AdFormat.ADFORMAT_NATIVE.getValue()).equals(creativeInfoVo.getAdFormat())){
            //原生创意
            if(!CollectionUtils.isEmpty(creativeInfoVo.getMaterials())){
                for (CreativeMaterial material:creativeInfoVo.getMaterials()){
                    //素材所属模板验证
                    if (material.getTemplateId()==null||material.getTemplateId()==0){
                        throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"templateId","Param.err.creative.material.templateId.not.null");
                    }
                    //素材类型验证
                    if (material.getMaterialType()==null||material.getMaterialType()==0){
                        throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"materialType","Param.err.creative.material.materialType.not.null");
                    }
                    //验证materialType是否有效
                    if (!new Integer(MaterialType.MATERIALTYPE_PICTURE.getValue()).equals(material.getMaterialType())
                            && !new Integer(MaterialType.MATERIALTYPE_TEXT.getValue()).equals(material.getMaterialType())){
                        throw new ParamValidateException(Result.ERR_INVALID_PARAMETER, "materialType", "Param.err.creative.material.materialType.invalid.parameter");
                    }
                    //如果是图片素材则验证图片url是否存在
                    if (new Integer(MaterialType.MATERIALTYPE_PICTURE.getValue()).equals(material.getMaterialType())
                            && (material.getUploadResourceId()==null||material.getUploadResourceId()==0)){
                        throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"uploadResourceId","Param.err.creative.material.uploadResourceId.not.null");
                    }
                    //如果是文本素材则验证文本内容是否为空
//                    if (new Integer(MaterialType.MATERIALTYPE_TEXT.getValue()).equals(material.getMaterialType())
//                            && StringUtils.isEmpty(material.getMaterialText())){
//                        throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"materialText","Param.err.creative.material.text.not.null");
//                    }
                    //验证occurs是否为空
                    if (material.getOccurs()==null||material.getOccurs()==0){
                        throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"occurs","Param.err.creative.material.occurs.not.null");
                    }
                }
            }else{
                throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"materials","Param.err.creative.materials.not.null");
            }
        }else if (new Integer(AdFormat.ADFORMAT_BANNER.getValue()).equals(creativeInfoVo.getAdFormat())
                || new Integer(AdFormat.ADFORMAT_INTERSTITINAL.getValue()).equals(creativeInfoVo.getAdFormat())
                || new Integer(AdFormat.ADFORMAT_SPREAD.getValue()).equals(creativeInfoVo.getAdFormat())){
            //非原生
            if (!CollectionUtils.isEmpty(creativeInfoVo.getMaterials())){
                for (CreativeMaterial material:creativeInfoVo.getMaterials()){
                    if (material.getUploadResourceId()==null||material.getUploadResourceId()==0){
                        throw new ParamValidateException(Result.ERR_MISS_PARAMETER,"uploadResourceId","Param.err.creative.material.uploadResourceId.not.null");
                    }
                }
            }
        }
    }
}
